@namespace BTCPayServer.Client
@using BTCPayServer.Abstractions.TagHelpers
@using BTCPayServer.TagHelpers
@using Microsoft.AspNetCore.Html
@using Microsoft.AspNetCore.Mvc.TagHelpers
@inject Security.ContentSecurityPolicies Csp
@model BTCPayServer.Controllers.UIManageController.ApiKeysViewModel
@{
	ViewData.SetLayoutModel(new LayoutModel(nameof(ManageNavPages.APIKeys), StringLocalizer["API Keys"])
        .SetCategory(nameof(ManageNavPages)));
	Csp.UnsafeEval();
}

<div class="sticky-header">
    <h2>@ViewData["Title"]</h2>
	<a id="page-primary" class="btn btn-primary" asp-action="AddApiKey" text-translate="true">
        Generate Key
    </a>
</div>
<partial name="_StatusMessage" />
<div class="row">
    <div class="col-xl-10 col-xxl-constrain">
        <p>
            @ViewLocalizer["The {0} offers programmatic access to your instance. You can manage your BTCPay Server (e.g. stores, invoices, users) as well as automate workflows and integrations (see {1}). For that you need the API keys, which can be generated here. Find more information in the {2}.",
                Html.ActionLink(StringLocalizer["Greenfield API"], "SwaggerDocs", "UIHome", new { }, new { target = "_blank",  rel = "noreferrer noopener" }),
                new HtmlString($"<a href=\"https://docs.btcpayserver.org/Development/GreenFieldExample/\" target=\"_blank\" rel=\"noreferrer noopener\">{StringLocalizer["use case examples"]}</a>"),
                Html.ActionLink(StringLocalizer["API authentication docs"], "SwaggerDocs", "UIHome", null, null, "section/Authentication", new { }, new { target = "_blank",  rel = "noreferrer noopener" })]
        </p>

        @if (Model.ApiKeyDatas.Any())
        {
            <table class="table table-lg">
                <thead>
                    <tr>
                        <th text-translate="true">Label</th>
                        <th text-translate="true" class="w-125px">Key</th>
                        <th text-translate="true">Permissions</th>
                        <th class="actions-col"></th>
                    </tr>
                </thead>
                <tbody>
                    @{
                        var index = 0;
                    }
                    @foreach (var keyData in Model.ApiKeyDatas)
                    {
                        <tr>
                            <td>@keyData.Label</td>
                            <td>
                                <code class="hide-when-js">@keyData.Id</code>
                                <button type="button" class="btn btn-link only-for-js p-0" data-reveal-btn text-translate="true">Reveal</button>
                                <div hidden class="gap-2 align-items-center">
                                    <code>@keyData.Id</code>
                                    <button type="button" class="btn btn-link d-flex p-0 clipboard-button" data-clipboard="@keyData.Id">
                                        <vc:icon symbol="actions-copy" />
                                    </button>
                                </div>
                            </td>
                            <td>
                                @{
                                    var permissions = keyData.GetBlob().Permissions;
                                }
                                @if (!permissions.Any())
                                {
                                    <span class="info-note text-warning">
                                        <vc:icon symbol="warning"/>
                                        <span text-translate="true">No permissions</span>
                                    </span>
                                }
                                else
                                {
                                    @foreach (var permission in Permission.ToPermissions(permissions).Select(c => c.ToString()).Distinct().ToArray())
                                    {
                                        <div><code class="text-break">@permission</code></div>
                                    }
                                }
                            </td>
                            <td>
                                <div class="d-flex align-items-center justify-content-end gap-1">
                                    <a asp-action="DeleteAPIKey" asp-route-id="@keyData.Id" asp-controller="UIManage" data-bs-toggle="modal" data-bs-target="#ConfirmModal" data-description="Any application using the API key <strong>@Html.Encode(keyData.Label ?? keyData.Id)</strong> will immediately lose access." data-confirm-input="@StringLocalizer["Delete"]" text-translate="true">Delete</a>
                                    <span>-</span>
                                    <button type="button" class="btn btn-link only-for-js p-0" data-qr="@index" text-translate="true">Show QR</button>
                                </div>
                            </td>
                        </tr>
                        index++;
                    }
                </tbody>
            </table>
        }
    </div>
</div>

<partial name="_Confirm" model="@(new ConfirmModel(StringLocalizer["Delete API key"], StringLocalizer["Any application using the API key will immediately lose access."], StringLocalizer["Delete"]))" />

<partial name="ShowQR" />

@section PageHeadContent {
    <link href="~/vendor/vue-qrcode-reader/vue-qrcode-reader.css" rel="stylesheet" asp-append-version="true" />
}
@section PageFootContent {
    <script src="~/vendor/vuejs/vue.min.js" asp-append-version="true"></script>
    <script src="~/vendor/vue-qrcode/vue-qrcode.min.js" asp-append-version="true"></script>
    <script src="~/vendor/ur-registry/urlib.min.js" asp-append-version="true"></script>
    <script src="~/vendor/vue-qrcode-reader/VueQrcodeReader.umd.min.js" asp-append-version="true"></script>

    <script>
        delegate('click', '[data-reveal-btn]', e => {
            const $container = e.target.parentElement.querySelector('[hidden]')
            e.target.setAttribute('hidden', 'true')
            $container.removeAttribute('hidden')
            $container.classList.add('d-inline-flex')
        })
        document.addEventListener("DOMContentLoaded", function () {
            const apiKeys = @Safe.Json(Model.ApiKeyDatas.Select(data => new
                            {
                                ApiKey = data.Id,
                                Host = Context.Request.GetAbsoluteRoot()
                            }));
            const qrApp = initQRShow({ title: "API Key QR" });
            delegate("click", "button[data-qr]", e => {
                e.preventDefault();
                const { qr } = e.target.dataset;
                const data = apiKeys[qr];
                qrApp.showData(JSON.stringify(data));
            });
        });
    </script>
}
